package com.atguigu.spzx.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.log.annotation.Log;
import com.atguigu.spzx.manager.mapper.SysRoleMapper;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.atguigu.spzx.common.utils.JwtUtil.createToken;


@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleUserMapper sysRoleUserMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();

        String redisCode = stringRedisTemplate.opsForValue().get("user:validate" + codeKey);
        if(!StringUtils.hasText(redisCode) ||!redisCode.equalsIgnoreCase(captcha)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        stringRedisTemplate.delete("user:validate" + codeKey);

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, userName);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        // SysUser sysUser = sysUserMapper.selectByUsername(userName);

        if (sysUser == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        String newPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!newPassword.equals(sysUser.getPassword())) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        String token = createToken(sysUser.getId(), sysUser.getUsername());

        stringRedisTemplate.opsForValue().set("user:login" + token, JSON.toJSONString(sysUser),7, TimeUnit.DAYS);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = stringRedisTemplate.opsForValue().get("user:login" + token);
        return JSON.parseObject(userJson, SysUser.class);
    }

    @Override
    public void logout(String token) {
        stringRedisTemplate.delete("user:login" + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

    @Override
    public IPage<SysUser> selectPage(Page<SysUser> page, SysUserDto sysUserDto) {
        String keyword = sysUserDto.getKeyword();
        String createTimeBegin = sysUserDto.getCreateTimeBegin();
        String createTimeEnd = sysUserDto.getCreateTimeEnd();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.hasText(keyword)){
            wrapper.like(SysUser::getUsername, keyword);
        }
        if(StringUtils.hasText(createTimeBegin)){
            wrapper.ge(SysUser::getCreateTime, createTimeBegin);
        }
        if(StringUtils.hasText(createTimeEnd)){
            wrapper.le(SysUser::getCreateTime, createTimeEnd);
        }
        wrapper.eq(SysUser::getIsDeleted, 0);
        wrapper.orderByDesc(SysUser::getId);
        return baseMapper.selectPage(page, wrapper);
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        String username = sysUser.getUsername();
        if(!StringUtils.hasText(username)){
            throw new GuiguException(ResultCodeEnum.NEED_USERNAME);
        }

        String password = sysUser.getPassword();
        if(!StringUtils.hasText(password)){
            throw new GuiguException(ResultCodeEnum.NO_PASSWORD);
        }

        SysUser dbSysUser = sysUserMapper.selectUserByUsername(username);
        if(dbSysUser != null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        password = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(password);
        sysUser.setStatus(1);
        sysUserMapper.save(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        String username = sysUser.getUsername();
        if(!StringUtils.hasText(username)){
            throw new GuiguException(ResultCodeEnum.NEED_USERNAME);
        }

        SysUser dbSysUser = sysUserMapper.selectUserByUsername(username);
        if(dbSysUser != null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        sysUserMapper.updateSysUser(sysUser);

    }
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "用户分配角色", businessType = 0)
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        //1 根据userId删除用户之前分配角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());

        //TODO 为了测试，模拟异常
        int a = 1/0;

        //2 重新分配新数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        //遍历得到每个角色id
        for(Long roleId:roleIdList) {
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        }
    }


}
